<template>
  <div class="resume">
    <div>
      <div class="title">
        <h1 style="color: #4D7181;font-size: 40px">求职意向</h1>
        <div>
          <FileSyncOutlined class="icon"/>
          <ZoomInOutlined class="icon"/>
        </div>

      </div>
    </div>
    <div style="border: 2px solid #4D7181; padding: 20px;border-top: 30px solid #4D7181; border-radius: 10px">


      <a-form
          ref="formRef"
          :label-col="labelCol"
          :model="formState"
          :rules="rules"
          :wrapper-col="wrapperCol"
      >
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">基本信息</a-divider>
        <div class="basic">

          <div class="basicInfo">
            <a-form-item ref="intentionName" label="姓名" name="intentionName" style="width: 200px">
              <a-input v-model:value="formState.intentionName" :bordered="isBordered"/>
            </a-form-item>
            <a-form-item ref="intentionStatus" label="状态" name="intentionStatus" style="width: 200px">
              <a-select v-model:value="formState.intentionStatus" :bordered="isBordered" placeholder="请选择意向状态！">
                <a-select-option value="公开">公开</a-select-option>
                <a-select-option value="隐藏">隐藏</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item ref="intentionHighestEducation" label="学历" name="intentionHighestEducation"
                         style="width:200px">
              <a-select v-model:value="formState.intentionHighestEducation" :bordered="isBordered" placeholder="请选择最高学历！">
                <a-select-option value="大专">大专</a-select-option>
                <a-select-option value="本科">本科</a-select-option>
                <a-select-option value="硕士">硕士</a-select-option>
                <a-select-option value="博士">博士</a-select-option>
              </a-select>
            </a-form-item>
            <br>
            <a-form-item ref="intentionMajor" label="专业" name="intentionMajor" style="width: 200px">
              <a-input v-model:value="formState.intentionMajor" :bordered="isBordered"/>
            </a-form-item>

            <a-form-item ref="intentionContactInfo" label="联系方式" name="intentionContactInfo">
              <a-input v-model:value="formState.intentionContactInfo" :bordered="isBordered" style="width: 300px"/>
            </a-form-item>
          </div>
          <div style="margin-right: 60px;">
            <router-link :to="{path:'/student/resume'}">
              <h2>查看简历</h2>
            </router-link>
          </div>
        </div>
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">求职意向</a-divider>
        <div class="school">
          <a-form-item ref="intentionJobTitle" label="求职岗位" name="intentionJobTitle" style="width: 250px">
            <a-input v-model:value="formState.intentionJobTitle" :bordered="isBordered"/>
          </a-form-item>
          <a-form-item ref="intentionExpectedSalary" label="期望薪资" name="intentionExpectedSalary" style="width: 250px">
            <a-input v-model:value="formState.intentionExpectedSalary" :bordered="isBordered"/>
          </a-form-item>
          <a-form-item ref="intentionJobType" label="工作性质" name="intentionJobType" style="width: 250px">
            <a-select v-model:value="formState.intentionJobType" :bordered="isBordered" placeholder="请期待工作性质！">
              <a-select-option value="全职">全职</a-select-option>
              <a-select-option value="兼职">兼职</a-select-option>
              <a-select-option value="实习">实习</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item ref="intentionLocation" label="期望工作地点" name="intentionLocation">
            <a-input v-model:value="formState.intentionLocation" :bordered="isBordered"/>
          </a-form-item>
          <a-form-item ref="intentionAvailableStartDate" label="可开始工作时间"
                       name="intentionAvailableStartDate" style="width: 400px">
            <a-date-picker v-model:value="formState.intentionAvailableStartDate" :bordered="isBordered"/>
          </a-form-item>
          <a-form-item ref="intentionAvailableStartDate" label="期望行业"
                       name="tagsList" style="width: 1000px">
            <a-select
                v-model:value="tagsList"
                mode="multiple"
                style="width: 100%"
                placeholder="Please select"
                :options="options1"
            />
          </a-form-item>
          <a-form-item ref="intentionAvailableStartDate" label="期望职位详情"
                       name="jobsList" style="width: 1000px">
            <a-select
                v-model:value="jobsList"
                mode="multiple"
                style="width: 100%"
                placeholder="Please select"
                :options="options2"
            />
          </a-form-item>

        </div>

        <a-col :span="24">
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <div>
              <div v-if="isSave">
                <div style="display:flex;">
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="save">
                    <a-button style="width:200px" type="primary">保存</a-button>
                  </a-popconfirm>
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                    <a-button danger style="margin-left: 60px; width:200px" type="primary">重置</a-button>
                  </a-popconfirm>
                </div>
              </div>
              <div v-else>
                <div v-if="isUpdate" style="display:flex;">
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="update">
                    <a-button style="width:200px" type="primary">保存</a-button>
                  </a-popconfirm>

                  <a-button style="margin-left: 60px; width:200px" @click="cancel">取消</a-button>

                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                    <a-button danger style="margin-left: 60px; width:200px" type="primary">重置</a-button>
                  </a-popconfirm>
                </div>
                <div v-else>
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定修改吗？" @confirm="isupdate">
                    <a-button style="width:200px" type="primary">修改</a-button>
                  </a-popconfirm>

                  <a-button style="margin-left: 60px; width:200px" @click="goBack">返回</a-button>

                </div>
              </div>
            </div>

          </a-form-item>
        </a-col>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import {h, onMounted, reactive, ref, toRaw} from 'vue';
//修改提示框
import {FileSyncOutlined, SmileOutlined, ZoomInOutlined} from '@ant-design/icons-vue';
//获取当前登录用户信息
import {useUserStore} from "@/stores/user.js";
import {
  queryResumeByStudentUserIdAPI,
} from "@/apis/student.js";
import {message, notification} from "ant-design-vue";
import moment from "moment";
import {useRouter} from 'vue-router';
import {creatIntentionAPI, queryIntentionByUserIdAPI, updateIntentionByIdAPI} from "@/apis/intention.js";
import {queryStudentByUserIdAPI} from "@/apis/user.js";
import Personal from "@/views/Student/layout/personal.vue";

const formRef = ref();
const formState = reactive({
  intentionUserId: '',
  intentionStudentId: '',
  intentionName: '',
  intentionContactInfo: '',
  intentionHighestEducation: '',
  intentionMajor: '',
  intentionJobTitle: '',
  intentionLocation: '',
  intentionExpectedSalary: '',
  intentionJobType: '',
  intentionAvailableStartDate: '',
  intentionStatus: '',
  tagsList: '',
  jobsList: '',
});
const rules = {
  intentionName: [
    {
      required: true,
      message: '请输入您的名字！',
      trigger: 'change',
    },
  ],
  intentionStatus: [
    {
      required: true,
      message: '请选择状态！',
      trigger: 'change',
    },
  ],
  intentionJobTitle: [
    {
      required: true,
      message: '请输入您期望的岗位！',
      trigger: 'change',
    },
  ],
  intentionExpectedSalary: [
    {
      required: true,
      message: '请输入您期望的薪资！',
      trigger: 'change',
    },
  ],
  intentionContactInfo: [
    {
      required: true,
      message: '请输入您的电话！',
      trigger: 'change',
    }
  ],
  intentionJobType: [
    {
      required: true,
      message: '请输入工作性质！',
      trigger: 'change',
    }
  ],
  intentionLocation: [
    {
      required: true,
      message: '请输入您期望工作地点！',
      trigger: 'change',
    }
  ],
  intentionMajor: [
    {
      required: true,
      message: '请输入您的专业！',
      trigger: 'change',
    }
  ],
  intentionAvailableStartDate: [
    {
      required: true,
      message: '可开始工作时间！',
      trigger: 'change',
    }
  ],
  tagsList: [
    {
      required: false,
      message: '求职期望行业！',
      trigger: 'change',
    }
  ],
  jobsList: [
    {
      required: false,
      message: '求职期望职位！',
      trigger: 'change',
    }
  ],
};

const useStore = useUserStore();
const save = () => {
  formRef.value
      .validate()
      .then(async () => {
        //获取到userID，去获取studentID
        formState.intentionUserId = useStore.userInfo.userId;
        const res = await queryStudentByUserIdAPI(formState.intentionUserId);
        formState.intentionStudentId = res.data.data.studentId;
        console.log("tagsList"+tagsList.value);
        console.log("jobsList"+jobsList.value);
        formState.tagsList=JSON.stringify(tagsList.value);
        formState.jobsList=JSON.stringify(jobsList.value);
        //保存求职意向
        const res1 = await creatIntentionAPI(formState);
        if (res1.data.flag) {
          success(res1.data.message);
          setTimeout(function () {
            location.reload(); // 刷新当前页面
          }, 1000);
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};
const isUpdate = ref(false);//是否修改
const isBordered = ref(false);//是否边框
const isupdate = () => {//修改按钮
  isUpdate.value = true;
  isBordered.value = true;
  openNotification();
}
const update = () => {

  formRef.value
      .validate()
      .then(async () => {
        formState.tagsList=JSON.stringify(tagsList.value);
        formState.jobsList=JSON.stringify(jobsList.value);
        const res = await updateIntentionByIdAPI(formState);
        console.log(res);
        if (res.data.flag) {
          success(res.data.message);
          // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
          setTimeout(function () {
            location.reload(); // 刷新当前页面
          }, 1000);
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};

const success = (msg) => {
  message.success(msg);
};

//重置后是否刷新
const isRefresh = ref(false);
const resetForm = () => {
  formRef.value.resetFields();
  isRefresh.value = true;
};

//控制按钮
const isSave = ref();//是否保存
//获取数据
//获取当前登录用户信息

const intentionUserId = ref(useStore.userInfo.userId);
const getData = async (intentionUserId) => {
  const res = await queryIntentionByUserIdAPI(intentionUserId.value)
  if (res.data.data == null) {
    isBordered.value = true
    isSave.value = true
    isUpdate.value = false;
  } else {
    isBordered.value = false
    isSave.value = false
    isUpdate.value = false;
  }
  const res1 = await queryResumeByStudentUserIdAPI(intentionUserId.value);
  formState.intentionName = res1.data.data.studentName;
  formState.intentionMajor = res1.data.data.studentMajor;
  formState.intentionContactInfo = res1.data.data.studentContact;
  formState.intentionHighestEducation = res1.data.data.studentHighestEducation;
  formState.intentionStatus = '公开';


  formState.intentionStudentId = res.data.data.intentionStudentId;
  formState.intentionUserId= res.data.data.intentionUserId;
  formState.intentionId = res.data.data.intentionId;
  formState.intentionName = res.data.data.intentionName;
  formState.intentionStatus = res.data.data.intentionStatus;
  formState.intentionContactInfo = res.data.data.intentionContactInfo;
  formState.intentionHighestEducation = res.data.data.intentionHighestEducation;
  formState.intentionMajor = res.data.data.intentionMajor;
  formState.intentionJobTitle = res.data.data.intentionJobTitle;
  formState.intentionLocation = res.data.data.intentionLocation;
  formState.intentionExpectedSalary = res.data.data.intentionExpectedSalary;
  formState.intentionJobType = res.data.data.intentionJobType;
  formState.intentionStatus = res.data.data.intentionStatus;
  formState.intentionAvailableStartDate = moment(res.data.data.intentionAvailableStartDate, 'YYYY-MM-DD');
  formState.tagsList = res.data.data.tagsList;
  formState.jobsList = res.data.data.jobsList;
  tagsList.value = JSON.parse(formState.tagsList)
  jobsList.value = JSON.parse(formState.jobsList)


}


//生命周期
onMounted(() => {
  getData(intentionUserId);
});

//上传照片
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
    formState.student_imgUrl = fileList.value[0].response.data;
    console.log(formState.student_imgUrl)

  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const openNotification = () => {
  notification.open({
    message: '温馨提示！！！',
    description:
        '点击输入框即可进行修改',
    icon: () =>
        h(SmileOutlined, {
          style: 'color: red',
        }),
  });
};

const router = useRouter();
const goBack = () => {
  router.go(-1); // -1 表示返回上一个页面
}
const cancel = () => {
  isSave.value = false;
  isUpdate.value = false;
  isBordered.value = false;
  if (isRefresh.value) {
    // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
    setTimeout(function () {
      location.reload(); // 刷新当前页面
    }, 500);
  }
}

const options1 = [];
const options2 = [];
const tags = ['互联网/AI', '服务/餐饮', '医疗/制药', '教育/培训', '金融/制造','游戏/电子','网络社交/媒体','房地产/建筑','零售/批发','行业不限'];
const jobs = ['测试工程师', '自动化测试', 'Java工程师', '功能测试', '测试开发','软件测试','全栈工程师','后端开发','前端工程师','实施工程师','运维工程师','算法工程师','大数据开发',
  '教师', '人力资源', '硬件工程师', '物流专员', '视频剪辑','运营专员','产品经理','项目经理','财务顾问','服装设计','建模工程师','教育培训','幼儿/少儿教师','银行专员','保险理赔',
  '厨师', '送餐员', '林业技术员', '服务员', '餐饮店长','酒店经理','医师','通信工程师','维修技术人员','房地产销售','园林设计','建筑工程师','广告制作','职位不限'];

for (let i = 0; i < tags.length; i++) {
  options1.push({
    label: tags[i], // 将单个标签值作为选项的标签
    value: tags[i], // 将单个标签值作为选项的值
    disabled: false // 根据实际需求设置是否禁用，这里先设置为 false
  });
}
for (let i = 0; i < jobs.length; i++) {
  options2.push({
    label: jobs[i], // 将单个标签值作为选项的标签
    value: jobs[i], // 将单个标签值作为选项的值
    disabled: false // 根据实际需求设置是否禁用，这里先设置为 false
  });
}
const tagsList = ref([]);
const jobsList = ref([]);

</script>
<style lang="scss" scoped>
.resume {
  margin: 5px;
  padding: 20px 60px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1);
  border-radius: 30px; /* 你可以调整这个值来改变圆角的大小 */

  .title {
    display: flex;
    justify-content: space-between;
    //border-bottom: 15px solid #4D7181;

    .icon {
      font-size: 35px;
      padding: 15px;
      color: white;
      margin-right: 20px;
      background-color: #C09E66;
      border-radius: 50px;
      margin-bottom: 10px;
    }
  }

  .basic {
    display: flex;
    padding-left: 30px;

    .basicInfo {
      height: 100%;
      display: flex;
      flex-wrap: wrap; /* 允许子元素换行 */
      gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
    }

    .update {
      margin-right: 100px;
    }
  }

  .school {
    width: 100%;
    padding-left: 30px;
    justify-content: space-between;
    display: flex;
    margin-bottom: 30px;
    flex-wrap: wrap; /* 允许子元素换行 */
    gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
  }
}

:deep(.ant-form-item) {
  margin-bottom: 10px;
}

:deep(.ant-upload-wrapper.ant-upload-picture-card-wrapper.ant-upload.ant-upload-select) {
  border: 0;
  height: 170px;
  width: 150px;
}

/* 如果组件不在 Shadow DOM 中 */
.ant-upload-wrapper.ant-upload-picture-card-wrapper.ant-upload.ant-upload-select {
  border: none; /* 移除边框 */
  height: 170px;
  width: 150px;
}

</style>

